<script setup lang="ts">
import { tableConfig } from './config/table-config';
import { message } from '@/components/q-message/message';
import { handleDelKey, isArray, checkRepeat, RepeatMsg } from '@/utils';
import { doAddPeriodList } from '@/api/base/workCalendar/workingHours/index';
import useEmit from '@/hooks/useEmitter';
import usePageSave from '@/hooks/usePageSave';
import type { WorkingHours } from '@/api/base/workCalendar/workingHours/model/type';
import type { TData } from '@/views/Base/WorkCalendar/common';

defineOptions({
    name: 'WorkingHoursAdd'
});

const { loading, modalOk, modalSlotRef: tableRef } = useModal();

const STORE_KEY = 'workingHoursAddData'; // store数据的key
const { startRecording, isUpdate } = useEmit(STORE_KEY); // 页面标签路由关闭二次确认事件监听 EventBus

useRecordData(tableRef, STORE_KEY, isUpdate, startRecording); // 复制工作时段相关

/**
 * 保存新增数据
 */
const handleSubmit = async () => {
    const tableData: TData[] = tableRef.value.getSaveData();

    // 处理数据
    const addData = tableData.map(item => {
        const gradeItem: Omit<TData, 'id' | 'name'> = handleDelKey(item, ['id', 'name']);
        const periods: Omit<WorkingHours, 'id' | 'name'> = { end1: '', start1: '' };

        Object.keys(gradeItem).forEach(key => {
            if (key in gradeItem) {
                if (isArray(gradeItem[key])) {
                    const endI = key[key.length - 1];
                    periods['start' + endI] = gradeItem[key]?.[0];
                    periods['end' + endI] = gradeItem[key]?.[1];
                }
            }
        });
        return {
            name: item.name,
            ...periods
        };
    });

    const msg = checkRepeat(addData, ['name']);

    // 判断名称重复
    if (msg) {
        const { value, line } = msg;
        RepeatMsg({ value, line, label: '工作时段名称' });
        return;
    }

    try {
        const res = await doAddPeriodList(addData);
        if (res) {
            message.success('新增时段成功！');
        }
        return res;
    } catch (error) {
        console.log('error', error);
    }
};

/**
 * 点击保存按钮
 */
const handleOk = async () => {
    try {
        await modalOk(handleSubmit);
        usePageSave('/workCalendar');
    } catch (e) {
        console.log(e);
    }
};
</script>

<template>
    <q-page>
        <base-table
            ref="tableRef"
            :add-table-row="true"
            :open-sticky="true"
            :show-fullscreen="true"
            :tableConfig="tableConfig"
        >
            <!-- 保存/取消 -->
            <template #tableHeadEnd>
                <q-submit-button
                    size="default"
                    :hide-label="true"
                    align="right"
                    :horizontal="true"
                    :loading="loading"
                    :cancel-button="false"
                    @save="handleOk"
                />
            </template>
        </base-table>
    </q-page>
</template>

<style lang="scss" scoped></style>
